package com.xiangge.es.service.impl;

import com.xiangge.es.dao.DocumentSearchRepository;
import com.xiangge.es.pojo.ESDocument;
import com.xiangge.es.service.DocumentSearchService;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;

/**
 * @author lsy_server
 */
@Service
public class DocumentSearchServiceImpl implements DocumentSearchService {

    @Autowired
    private DocumentSearchRepository documentSearchRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * get document list by name and id order by orderField parameter
     *
     * @param name       queried name
     * @param projectId  contained project id
     * @param orderField order filed  name
     * @return document list
     */
    @Override
    public List<ESDocument> getDocumentsByNameOrderByCreateOn(String name, String
            projectId, String orderField) {
        List<ESDocument> ESDocuments;
        try {
            SearchQuery searchQuery = new NativeSearchQueryBuilder()
                    .withQuery(matchQuery("name", name))
                    .withFilter(matchPhraseQuery("projectId", projectId))
                    .withSort(SortBuilders.scoreSort().order(SortOrder.DESC))
                    .withSort(new FieldSortBuilder(orderField).order(SortOrder.DESC))
                    .build();
            ESDocuments = elasticsearchTemplate.queryForList(searchQuery,
                    ESDocument.class);
        } catch (Exception e) {
            throw new RuntimeException();
        }
        return ESDocuments;
    }

    @Override
    public List<ESDocument> findByName(String name) {
        NativeSearchQuery query = new NativeSearchQueryBuilder()
                .withQuery(matchQuery("name", name))
                .withSort(SortBuilders.fieldSort("addTime").order(SortOrder.DESC))
                .build();
        List<ESDocument> esDocuments = elasticsearchTemplate.queryForList(query, ESDocument.class);
        return esDocuments;
    }
}